package com.chj.consumer_balance.qos;

import com.chj.consumer_balance.getmessage.GetMessageProducer;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 普通的消费者
 */
public class QosConsumerMain {
    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("10.200.169.5");
        connectionFactory.setVirtualHost("chj_vhost");
        connectionFactory.setUsername("chj");
        connectionFactory.setPassword("123456");
        // 创建连接
        Connection connection = connectionFactory.newConnection();
        final Channel channel = connection.createChannel();
        // 创建交换器 BuiltinExchangeType.DIRECT == direct
        channel.exchangeDeclare(GetMessageProducer.EXCHANGE_NAME, BuiltinExchangeType.DIRECT);
        // 声明一个队列
        String queueName = "focuserror";
        channel.queueDeclare(queueName, false, false, false, null);
        //只关注error级别的日志，然后记录到文件中去。
        String routekey = "error";
        channel.queueBind(queueName, GetMessageProducer.EXCHANGE_NAME, routekey);
        System.out.println("waiting for message........");
        /*声明了一个消费者*/
        final Consumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag,
                                       Envelope envelope,
                                       AMQP.BasicProperties properties,
                                       byte[] body) throws IOException {
                String message = new String(body, "UTF-8");
                System.out.println("Received["+envelope.getRoutingKey() +"]"+message);
                // TODO 单条确认
//                channel.basicAck(envelope.getDeliveryTag(),true);
            }
        };
        //TODO 如果是两个消费者(QOS ,批量)则轮询获取数据
        // global参数:true\false是否将上面设置应用于channel，简单点说，就是上面限制是channel 级别的还是consumer级别。
        //TODO 15条预取(15条都取出来 15， 21-15  6 )
//        channel.basicQos(15, false); // Per consumer limit
        channel.basicQos(15, true); // Per channel limit
        // 消费者正式开始在指定队列上消费消息
        channel.basicConsume(queueName,false,consumer);
        // TODO 自定义消费者批量确认
//        BatchAckConsumer batchAckConsumer = new BatchAckConsumer(channel);
//        channel.basicConsume(queueName,false,batchAckConsumer);
    }
}
